import React, { Component } from "react";
import MainLayout from "@component/mainLayout/mainLayout";
import Button from "@component/button/index";
import { InputItem, Toast, Modal, Picker, List } from "antd-mobile";
import "./style.scss";
import sendCode from "@component/sendCode/index";
import BankItem from "./component/BankItem";
import { InterfaceG, agreements_url } from "@config/Config";
import yhTools from "@tools/yh";
import icon_camera from "@images/icon/icon-camera.png";
import Banner from "@/views/viewCommon/Banner";
import moment from "moment";
const submitCardRegexp = value => value.replace(/\s*/g, "");
const checkPhoneReg = value => /^1[3456789]\d{9}$/.test(value);
const checkBankReg = value => /^\d{13,19}$/.test(value);
const checkIdCard = value => /(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value);

/**
 * 快捷支付绑卡
 */
@sendCode()
class BindCard extends Component {
	constructor(props) {
		super(props);
		this.state = {
			idCard: "", //身份证
			isVisible: false, //是否显示
			accountNo: "", //银行卡号
			verifyCode: "", //验证码
			userBankPhone: "", //手机号码
			isBackModalVisible: false, //是否显示返回弹出层
			hasSendCode: false, //是否发送验证码
			bannerList: [], //头部banner
			accountType: "2", //银行卡类型
			spaceID: ""
		};
	}
	/*******************生命周期 start************************/
	componentDidMount = () => {
		console.log("this.props.location", this.props.location);
		const { query = {} } = this.props.location;

		//先查看是否有缓存页面数据，有就填充页面
		let cache_fastPayment_bindCard_info = sessionStorage.getItem(
			"cache_fastPayment_bindCard_info"
		);
		if (cache_fastPayment_bindCard_info) {
			let fastPayment_bindCard_info = JSON.parse(
				cache_fastPayment_bindCard_info
			);

			//如果发送了验证码，跳转页面后回来继续倒计时
			if (fastPayment_bindCard_info.hasSendCode) {
				let cuttentTime = moment().format("YYYY-MM-DD HH:mm:ss");
				let cacheTime = moment(fastPayment_bindCard_info.cacheTime);
				let countTime = moment(cuttentTime).diff(cacheTime, "seconds");
				const { sendCode, setCountDown } = this.props.sendCode;
				let countDownValue = fastPayment_bindCard_info.countDownValue;
				let resultTime = countDownValue - countTime;
				if (resultTime > 0) {
					setCountDown(resultTime);
					sendCode();
				}
				console.log("countDownValue", countDownValue);
				console.log("cuttentTime", cuttentTime);
				console.log("cacheTime", fastPayment_bindCard_info.cacheTime);
				console.log("countTime", countTime);
				console.log("resultTime", resultTime);
			}

			console.log("fastPayment_bindCard_info", fastPayment_bindCard_info);
			this.setState(
				{
					...fastPayment_bindCard_info
				},
				() => {
					this.initData();
				}
			);
		} else {
			this.setState({
				from: query.from
			});
			this.initData();
		}
	};

	componentWillUnmount() {
		if (window.YHAuthorize) {
			window.YHAuthorize.View.removeEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
	}
	/*******************生命周期 end************************/

	/*******************业务方法 start************************/
	/**
	 * @msg:初始化页面数据
	 * @param {*}
	 * @return {*}
	 */
	initData = () => {
		Toast.loading("加载中", 100);
		let bankCard_selectTowElementInfoByUserCode = this.bankCard_selectTowElementInfoByUserCode();
		let getBannerList = this.getBannerList();
		Promise.all([
			bankCard_selectTowElementInfoByUserCode,
			getBannerList
		]).finally(() => {
			Toast.hide();
		});

		//软键盘处理
		if (window.YHAuthorize) {
			window.YHAuthorize.View.addEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
		let _tempRandom = Math.round(Math.random() * 1000000);
		this.setState({
			spaceID: _tempRandom
		});
	};

	/**
	 * @msg: 键盘事件
	 * @param {*} obj
	 * @return {*}
	 */
	keyboardEvent = obj => {
		const id = document.activeElement.getAttribute("id");
		if (id !== "fix-cursor") {
			let winHeight = document.documentElement.clientHeight;
			if (document.getElementById(`keybordb_${this.state.spaceID}`)) {
				document.getElementById(`keybordb_${this.state.spaceID}`).style.height =
					(winHeight * obj.heightper) / 2 + 74 + "px";
			}
		}
		if (id === "js-fix-bug") {
			document.activeElement.scrollIntoView();
		}
	};

	/**
	 * @msg: 查询可用银行卡列表
	 * @param {*}
	 * @return {*}
	 */
	bankCard_queryAvailableBankCardList = () => {
		Toast.loading("加载中", 100);
		const params = {
			url: InterfaceG.bankCard_queryAvailableBankCardList,
			params: {
				channelCode: "huatong"
			}
		};
		yhTools.request(params).then(res => {
			const { code, data = {} } = res;
			if (code === "0") {
				this.setState(
					{
						bankCardList: data
					},
					() => {
						this.toggleVisible(true);
					}
				);
				Toast.hide();
			} else {
				Toast.info(res.message, 2);
			}
		});
	};

	/**
	 * @msg: 二要素查询
	 * @param {*}
	 * @return {*}
	 */
	bankCard_selectTowElementInfoByUserCode = () => {
		return new Promise((resolve, reject) => {
			const params = {
				url: InterfaceG.bankCard_selectTowElementInfoByUserCode
			};
			yhTools.request(params).then(res => {
				const { code, data = {} } = res;
				let is_userName = false;
				let is_idCard = false;
				if (data.userName) {
					is_userName = true;
				}
				if (data.idNo) {
					is_idCard = true;
				}
				if (code === "0") {
					this.setState({
						userName: data.userName,
						idCard: data.idNo,
						is_userName,
						is_idCard
					});
				}
				resolve();
			});
		});
	};

	/**
	 * @msg: 获取图片配置banner
	 * @param {*}
	 * @return {*}
	 */
	getBannerList() {
		return new Promise((resolve, reject) => {
			let params = {
				url: InterfaceG.getBannerListByPageType,
				params: {
					pageType: "QUICK_SIGN_BIND_PAGE"
				}
			};
			yhTools.request(params).then(res => {
				if (res.code === "0") {
					if (res.data && res.data.length > 0) {
						res.data.forEach(item => {
							if (item.bannerType == "QUICK_SIGN_BIND_TOP_BANNER") {
								this.setState({
									bannerList: item.indexServerDtos ? item.indexServerDtos : []
								});
							}
						});
					}
				}
				resolve();
			});
		});
	}

	/**
	 * @msg: 选择图片
	 * @param {*}
	 * @return {*}
	 */
	chooseImage() {
		//打开原生获取图片
		let imgPicker = {
			type: "3", //相机和相册
			imageName: this.props.mobile + "_card_" + ".png",
			imageSize: 100 * 1024 + "", // 100kb,自定义
			thumbnailSize: 100 * 1024 + "" // 100kb,自定义
		};

		yhTools.chooseImage(imgPicker).then(
			resp => {
				this.getOcrBank(resp.data.path);
			},
			() => {}
		);
	}

	/**
	 * @msg: 获取ocr银行卡
	 * @param {*} path
	 * @return {*}
	 */
	getOcrBank(path) {
		const imageData = {
			name: "bankImg.jpeg",
			path: path,
			params: {}
		};
		const objs = {
			url: InterfaceG.orcBank,
			imageArray: [imageData]
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				this.setState({
					bankInfo: res.data,
					accountNo: res.data.cardNumber
						.replace(/\s/g, "")
						.replace(/(\w{4})(?=\w)/g, "$1 ")
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	}

	toggleVisible = isVisible => {
		this.setState({
			isVisible
		});
	};

	/**
	 * @msg: 查询银行卡类型（储蓄卡/信用卡）
	 * @param {*}
	 * @return {*}
	 */
	bankCard_selectCardType = async () => {
		const { accountNo } = this.state;
		if (!checkBankReg(submitCardRegexp(accountNo))) {
			Toast.info("请输入正确的银行卡号", 2);
			return false;
		}

		const params = {
			url: InterfaceG.bankCard_selectCardType,
			params: {
				accountNo: submitCardRegexp(accountNo)
			}
		};
		return await yhTools.request(params).then(res => {
			const { code, data = {} } = res;
			if (code === "0") {
				return data.cardType;
			} else {
				Toast.hide();
				Toast.info(res.message, 2);
				return false;
			}
		});
	};

	/**
	 * @msg: 检查输入信息
	 * @param {*} async
	 * @return {*}
	 */
	isCansendMsgCode = async () => {
		const {
			accountNo,
			userBankPhone,
			idCard,
			userName,
			creditcardCvv2,
			creditcardDeadline,
			bankCardType,
			is_idCard
		} = this.state;
		if (!userName) {
			Toast.info("请输入姓名", 2);
			return false;
		}
		if (!idCard) {
			Toast.info("请输入身份证", 2);
			return false;
		}
		if (!is_idCard && !checkIdCard(submitCardRegexp(idCard))) {
			Toast.info("身份证格式不正确", 2);
			return false;
		}
		if (!bankCardType) {
			Toast.info("请选择银行卡类型", 2);
			return false;
		}
		if (!accountNo) {
			Toast.info("请输入银行卡号", 2);
			return false;
		}
		Toast.loading("加载中...", 100);
		let accountType = await this.bankCard_selectCardType();
		console.log("accountType", accountType);
		console.log("bankCardType", bankCardType);
		this.setState({
			accountType
		});
		if (!accountType) {
			return false;
		} else {
			if (!checkBankReg(submitCardRegexp(accountNo))) {
				Toast.hide();
				Toast.info("请输入正确的银行卡号", 2);
				return false;
			}
			if (accountType !== bankCardType) {
				Toast.hide();
				Toast.info("所选银行卡类型与输入银行卡号不一致", 2);
				return false;
			}
			if (bankCardType === "3") {
				if (!creditcardDeadline) {
					Toast.hide();
					Toast.info("请输入卡片正面4位有效期数字", 2);
					return false;
				}
				if (!creditcardCvv2) {
					Toast.hide();
					Toast.info("请输入卡片背面3位数验证码", 2);
					return false;
				}
			}
			if (!userBankPhone) {
				Toast.hide();
				Toast.info("请填写手机号", 2);
				return false;
			}
			if (!checkPhoneReg(submitCardRegexp(userBankPhone))) {
				Toast.hide();
				Toast.info("手机号格式不正确", 2);
				return false;
			}
			return true;
		}
	};

	/**
	 * @msg: 确认绑定快捷支付
	 * @param {*}
	 * @return {*}
	 */
	bindCard = async () => {
		let canSubmit = await this.isCansendMsgCode();
		if (canSubmit) {
			const {
				accountNo,
				verifyCode,
				hasSendCode,
				userBankPhone,
				idCard,
				userName,
				orderNo,
				from,
				accountType,
				creditcardCvv2,
				creditcardDeadline
			} = this.state;
			if (!hasSendCode) {
				Toast.hide();
				Toast.info("请获取验证码", 2);
				return false;
			}
			if (!verifyCode.length) {
				Toast.hide();
				Toast.info("请输入验证码");
				return false;
			}
			if (verifyCode.length !== 6) {
				Toast.hide();
				Toast.info("验证码输入错误");
				return false;
			}

			let url = InterfaceG.bankCard_bindCardAndSign;
			/* if (from === "cashier") {
				//从收银台过来签约也只先签约，因为上海生活APP那边把需求理解错了，他们那边做需求变更要走很多流程，很麻烦
				url = InterfaceG.bankCard_bindCardAndSign;
			} else if (from === "membershipCode") {
				//从会员码过来只签约
				url = InterfaceG.bankCard_bindCardAndSign;
			} */
			let objs = {
				url,
				params: {
					userName: submitCardRegexp(userName),
					cardId: submitCardRegexp(idCard),
					accountNo: submitCardRegexp(accountNo),
					verifyCode: submitCardRegexp(verifyCode),
					userBankPhone: submitCardRegexp(userBankPhone),
					orderNo,
					scene: "07",
					signType: "02",
					accountType,
					creditcardCvv2,
					creditcardDeadline
				}
			};
			yhTools.request(objs).then(res => {
				Toast.hide();
				const { code, data = {} } = res;
				if (code === "0") {
					if (from === "cashier") {
						//let tradeNo = data && data.tradeNo;
						//从收银台过来跳转到倒计时页面 上海生活APP那边把需求理解错了，暂时注释，这是一键支付成功跳转逻辑
						/* this.props.history.push({
							pathname: "/fastPayment/inProcess",
							query: {
								tradeNo
							}
						}); */

						Toast.info("绑卡成功", 2);
						setTimeout(() => {
							yhTools.bindCardSuccess(submitCardRegexp(accountNo));
						}, 2000);
					} else if (from === "membershipCode") {
						//从会员码过来通知生活并关闭sdk回到会员码
						Toast.info("绑卡成功", 2);
						setTimeout(() => {
							yhTools.bindCardSuccess(submitCardRegexp(accountNo));
						}, 2000);
					}
					//页面不需要关闭 不返回生活的code=1
				} else if (code === "1") {
					Toast.info(res.message, 2);
				} else {
					Toast.info(res.message, 2);
					setTimeout(() => {
						yhTools.bindCardFailed(res.message);
					}, 2000);
				}
			});
		}
	};

	/**
	 * @msg: 改变输入框的值
	 * @param {*} key 对应的state
	 * @param {*} value 值
	 * @return {*}
	 */
	InputOnChange = (key, value) => {
		this.setState({
			[key]: value
		});
	};

	/**
	 * @msg: 银行卡类型变化
	 * @param {*} v 银行卡值
	 * @return {*}
	 */
	bankCardTypeChange = v => {
		let bankCardType = v[0];
		this.setState({
			bankCardTypeValue: v,
			bankCardType
		});
	};
	/*******************业务方法 end************************/

	/*******************点击事件 start************************/

	/**
	 * @msg:发送验证码
	 * @param {*}
	 * @return {*}
	 */
	sendMsgCode = async () => {
		const { sendCode, isClick, setCountDown } = this.props.sendCode;
		if (!isClick) return;
		let canSubmit = await this.isCansendMsgCode();
		console.log("canSubmit", canSubmit);
		if (canSubmit) {
			const {
				accountNo,
				userBankPhone,
				idCard,
				userName,
				creditcardCvv2,
				creditcardDeadline,
				accountType
			} = this.state;
			let objs = {
				url: InterfaceG.bankCard_bindCardAndSignSendCode,
				params: {
					mobilePhone: submitCardRegexp(userBankPhone),
					userName: submitCardRegexp(userName),
					accountNo: submitCardRegexp(accountNo),
					cardId: submitCardRegexp(idCard),
					scene: "07",
					signType: "02",
					accountType,
					creditcardCvv2,
					creditcardDeadline
				}
			};

			yhTools.request(objs).then(res => {
				Toast.hide();
				if (res.code === "0") {
					sendCode();
					const { orderNo } = res.data;
					this.setState({
						orderNo,
						hasSendCode: true
					});
				} else {
					Toast.info(res.message, 2);
				}
			});
		}
	};

	/**
	 * @msg: 查看协议
	 * @param {*} type
	 * @return {*}
	 */
	openContract = type => {
		//跳页面去缓存页面数据
		const {
			from,
			userName,
			idCard,
			bankCardTypeValue,
			accountNo,
			creditcardDeadline,
			creditcardCvv2,
			userBankPhone,
			hasSendCode,
			verifyCode,
			orderNo
		} = this.state;
		const { countDownValue } = this.props.sendCode;
		let cacheTime = moment().format("YYYY-MM-DD HH:mm:ss");
		console.log("countDownValue", countDownValue);
		console.log("cacheTime", cacheTime);
		let cache_fastPayment_bindCard_info = JSON.stringify({
			from,
			userName,
			idCard,
			bankCardTypeValue,
			bankCardType:
				bankCardTypeValue &&
				bankCardTypeValue.length > 0 &&
				bankCardTypeValue[0],
			accountNo,
			creditcardDeadline,
			creditcardCvv2,
			userBankPhone,
			hasSendCode,
			verifyCode,
			orderNo,
			countDownValue,
			cacheTime
		});
		sessionStorage.setItem(
			"cache_fastPayment_bindCard_info",
			cache_fastPayment_bindCard_info
		);
		this.props.history.push({
			pathname: "/iframeAgreements",
			state: {
				src:
					agreements_url +
					"/fastPayment/expressAgreement/expressAgreement.html",
				title: "快捷支付服务协议"
			}
		});
	};

	/**
	 * @msg: 确认绑定快捷支付点击
	 * @param {*}
	 * @return {*}
	 */
	bindCardClick = () => {
		yhTools.debounceNew(this.bindCard(), 200);
	};

	/**
	 * @msg: 取消绑卡
	 * @param {*}
	 * @return {*}
	 */
	cancelOrder() {
		yhTools.bindCardFailed("取消绑卡");
	}
	/*******************点击事件 end************************/

	render() {
		const {
			isVisible,
			userBankPhone,
			accountNo,
			hasSendCode,
			idCard,
			userName,
			bannerList,
			bankCardList,
			is_userName,
			is_idCard,
			bankCardType,
			bankCardTypeValue,
			creditcardDeadline,
			creditcardCvv2,
			verifyCode
		} = this.state;
		const _pageParams = {
			header: {
				title: "绑卡",
				headerBackground: "#fff",
				titleColor: "#232323",
				rightButt: "支持银行列表",
				rightButtColor: "#353535",
				newBackButt: true,
				rightButtCallBack: () => {
					this.bankCard_queryAvailableBankCardList();
				},
				goBackAction: () => {
					this.cancelOrder();
				}
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles
		};
		const { countDown, isClick } = this.props.sendCode;
		return (
			<MainLayout pageParams={_pageParams}>
				<div className="page-bindCard">
					<div className="bindCard-container">
						{bannerList.length > 0 && (
							<Banner
								className="header-img"
								bannerList={bannerList}
								history={this.props.history}
							/>
						)}

						<InputItem
							clear
							className={"my-input " + (is_userName ? "disabled" : "")}
							value={userName}
							disabled={is_userName}
							placeholder="请输入姓名"
							id="js-fix-bug"
							onChange={this.InputOnChange.bind(this, "userName")}
						>
							姓名
						</InputItem>
						<InputItem
							clear
							className={"my-input " + (is_idCard ? "disabled" : "")}
							maxLength={18}
							type="text"
							id="js-fix-bug"
							placeholder="请输入身份证号码"
							value={idCard}
							disabled={is_idCard}
							onChange={this.InputOnChange.bind(this, "idCard")}
						>
							身份证号码
						</InputItem>
						<Picker
							className="my-picker"
							data={[
								{ label: "储蓄卡", value: "2" },
								{ label: "信用卡", value: "3" }
							]}
							cols={1}
							value={bankCardTypeValue}
							onChange={v => this.bankCardTypeChange(v)}
						>
							<List.Item className="my-picker-list" arrow="horizontal">
								银行卡类型
							</List.Item>
						</Picker>
						{/* 23包括空格 */}
						<InputItem
							maxLength="23"
							className="my-input my-accountNo"
							placeholder="请输入银行卡号"
							type="bankCard"
							id="js-fix-bug"
							clear
							value={accountNo}
							onChange={this.InputOnChange.bind(this, "accountNo")}
						>
							银行卡号
							<img
								src={icon_camera}
								className="icon-item icon-camera"
								onClick={() => this.chooseImage()}
							/>
						</InputItem>
						{bankCardType === "3" && (
							<React.Fragment>
								<InputItem
									clear
									maxLength={4}
									type="text"
									id="js-fix-bug"
									placeholder="卡片正面4位有效期数字"
									className="my-input"
									onChange={this.InputOnChange.bind(this, "creditcardDeadline")}
									value={creditcardDeadline}
								>
									卡片有效期
								</InputItem>
								<InputItem
									clear
									maxLength={3}
									type="text"
									id="js-fix-bug"
									placeholder="卡片背面3位数验证码"
									className="my-input"
									onChange={this.InputOnChange.bind(this, "creditcardCvv2")}
									value={creditcardCvv2}
								>
									卡验证码
								</InputItem>
							</React.Fragment>
						)}
						<InputItem
							clear
							type="phone"
							id="js-fix-bug"
							placeholder="请填写预留手机号"
							value={userBankPhone}
							className="my-input"
							onChange={this.InputOnChange.bind(this, "userBankPhone")}
						>
							预留手机号
						</InputItem>
						<InputItem
							clear
							placeholder="请输入验证码"
							maxLength={6}
							minLength={6}
							id="js-fix-bug"
							pattern="[0-9]{6}"
							type="tel"
							className="my-input my-verifyCode"
							onChange={this.InputOnChange.bind(this, "verifyCode")}
							value={verifyCode}
						>
							验证码
							<span className="get-code" onClick={this.sendMsgCode}>
								{isClick
									? hasSendCode
										? "重新发送"
										: "获取验证码"
									: countDown}
							</span>
						</InputItem>
					</div>
					<div className="bindCard-bottom">
						<div className="bottom-agree">
							<p className="agree-p">
								<span className="agree-p-word">
									点击按钮，表示您已阅读并同意
								</span>
								<a
									className="agree-p-link"
									onClick={() => this.openContract("1")}
								>
									《快捷支付服务协议》
								</a>
							</p>
						</div>
						<div className="bottom-button">
							<Button onClick={this.bindCardClick}>确认绑定</Button>
						</div>

						<div id={"keybordb_" + this.state.spaceID}></div>
					</div>
				</div>

				<Modal
					visible={isVisible}
					transparent
					maskClosable={true}
					title="银行卡支持列表"
					closable={true}
					onClose={() => this.toggleVisible(false)}
					className="bank-list-modal"
				>
					<div style={{ height: 300, overflow: "scroll" }}>
						{console.log("bankCardList", bankCardList)}
						{bankCardList &&
							bankCardList.length > 0 &&
							bankCardList.map(item => {
								return <BankItem item={item} key={Math.random()} />;
							})}
					</div>
				</Modal>
			</MainLayout>
		);
	}
}
export default BindCard;
